const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const { User } = require('../models')
const auth = require('../middleware/auth')
const logger = require('../utils/logger')

/**
 * @api {post} /api/auth/login 用户登录
 * @apiDescription 用户登录接口
 * @apiName Login
 * @apiGroup Auth
 * @apiParam {String} phone 手机号
 * @apiParam {String} password 密码
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 用户信息和token
 */
router.post('/login', async (req, res) => {
  try {
    const { phone, password } = req.body

    if (!phone || !password) {
      return res.status(400).json({
        success: false,
        message: '手机号和密码不能为空'
      })
    }

    // 查询用户
    const user = await User.findOne({
      where: { phone, status: 1 }
    })

    if (!user) {
      return res.status(401).json({
        success: false,
        message: '用户不存在或已被禁用'
      })
    }

    // 验证密码
    const isPasswordValid = await user.verifyPassword(password)
    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        message: '密码错误'
      })
    }

    // 生成token
    const token = jwt.sign(
      { id: user.id },
      process.env.JWT_SECRET || 'your-jwt-secret',
      { expiresIn: '7d' }
    )

    // 更新最后登录时间
    await user.update({ lastLogin: new Date() })

    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          id: user.id,
          phone: user.phone,
          nickname: user.nickname,
          avatar: user.avatar,
          gender: user.gender,
          points: user.points,
          memberLevel: user.member_level,
          invitationCode: user.invitation_code,
          role: user.role,
          status: user.status
        }
      }
    })
  } catch (error) {
    logger.error('Login error:', error)
    res.status(500).json({
      success: false,
      message: '登录失败，请稍后再试'
    })
  }
})

/**
 * @api {post} /api/auth/register 用户注册
 * @apiDescription 用户注册接口
 * @apiName Register
 * @apiGroup Auth
 * @apiParam {String} phone 手机号
 * @apiParam {String} password 密码
 * @apiParam {String} verifyCode 验证码
 * @apiParam {String} invitationCode 邀请码(可选)
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 用户信息和token
 */
router.post('/register', async (req, res) => {
  try {
    const { phone, password, verifyCode, invitationCode } = req.body

    if (!phone || !password) {
      return res.status(400).json({
        success: false,
        message: '手机号和密码不能为空'
      })
    }

    // 验证码校验(实际项目中需要实现)
    if (!verifyCode || verifyCode !== '1234') {
      return res.status(400).json({
        success: false,
        message: '验证码错误'
      })
    }

    // 检查手机号是否已注册
    const existingUser = await User.findOne({
      where: { phone }
    })

    if (existingUser) {
      return res.status(400).json({
        success: false,
        message: '该手机号已注册'
      })
    }

    // 处理邀请码
    let inviterId = null
    if (invitationCode) {
        const inviter = await User.findOne({
          where: { invitationCode: invitationCode }
        })

      if (inviter) {
        inviterId = inviter.id
      }
    }

    // 生成用户邀请码
    const generateInvitationCode = () => {
      const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      let code = ''
      for (let i = 0; i < 6; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      return code
    }

    // 创建用户
    const user = await User.create({
      phone,
      password,
      nickname: `用户${phone.substring(phone.length - 4)}`,
      invitation_code: generateInvitationCode(),
      inviter_id: inviterId,
      status: 1
    })

    // 生成token
    const token = jwt.sign(
      { id: user.id },
      process.env.JWT_SECRET || 'your-jwt-secret',
      { expiresIn: '7d' }
    )

    res.json({
      success: true,
      message: '注册成功',
      data: {
        token,
        user: {
          id: user.id,
          phone: user.phone,
          nickname: user.nickname,
          avatar: user.avatar,
          gender: user.gender,
          points: user.points,
          memberLevel: user.member_level,
          invitationCode: user.invitation_code
        }
      }
    })
  } catch (error) {
    logger.error('Register error:', error)
    res.status(500).json({
      success: false,
      message: '注册失败，请稍后再试'
    })
  }
})

/**
 * @api {post} /api/auth/send-verify-code 发送验证码
 * @apiDescription 发送手机验证码
 * @apiName SendVerifyCode
 * @apiGroup Auth
 * @apiParam {String} phone 手机号
 * @apiParam {String} type 验证码类型(register, login, reset)
 * @apiSuccess {Boolean} success 是否成功
 */
router.post('/send-verify-code', async (req, res) => {
  try {
    const { phone, type } = req.body

    if (!phone) {
      return res.status(400).json({
        success: false,
        message: '手机号不能为空'
      })
    }

    if (!['register', 'login', 'reset'].includes(type)) {
      return res.status(400).json({
        success: false,
        message: '无效的验证码类型'
      })
    }

    // 模拟发送验证码
    // 实际项目中需要接入短信服务
    const verifyCode = '1234'

    res.json({
      success: true,
      message: '验证码发送成功',
      data: {
        verifyCode // 实际项目中不应返回验证码
      }
    })
  } catch (error) {
    logger.error('Send verify code error:', error)
    res.status(500).json({
      success: false,
      message: '发送验证码失败，请稍后再试'
    })
  }
})

/**
 * @api {post} /api/auth/reset-password 重置密码
 * @apiDescription 重置用户密码
 * @apiName ResetPassword
 * @apiGroup Auth
 * @apiParam {String} phone 手机号
 * @apiParam {String} verifyCode 验证码
 * @apiParam {String} newPassword 新密码
 * @apiSuccess {Boolean} success 是否成功
 */
router.post('/reset-password', async (req, res) => {
  try {
    const { phone, verifyCode, newPassword } = req.body

    if (!phone || !verifyCode || !newPassword) {
      return res.status(400).json({
        success: false,
        message: '手机号、验证码和新密码不能为空'
      })
    }

    // 验证码校验(实际项目中需要实现)
    if (verifyCode !== '1234') {
      return res.status(400).json({
        success: false,
        message: '验证码错误'
      })
    }

    // 查询用户
    const user = await User.findOne({
      where: { phone, status: 1 }
    })

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在或已被禁用'
      })
    }

    // 更新密码
    await user.update({ password: newPassword })

    res.json({
      success: true,
      message: '密码重置成功'
    })
  } catch (error) {
    logger.error('Reset password error:', error)
    res.status(500).json({
      success: false,
      message: '重置密码失败，请稍后再试'
    })
  }
})

/**
 * @api {post} /api/auth/wechat-login 微信登录
 * @apiDescription 微信登录接口
 * @apiName WechatLogin
 * @apiGroup Auth
 * @apiParam {String} code 微信授权码
 * @apiParam {Object} userInfo 微信用户信息(可选)
 * @apiParam {String} platform 平台类型
 * @apiParam {String} invitationCode 邀请码(可选)
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 用户信息和token
 */
router.post('/wechat-login', async (req, res) => {
  try {
    const { code, userInfo, platform, invitationCode } = req.body

    if (!code) {
      return res.status(400).json({
        success: false,
        message: '微信授权码不能为空'
      })
    }

    // 模拟微信登录 - 使用固定的测试用户数据
    // 实际项目中需要调用微信API获取openid和unionid
    const testOpenid = 'test_openid_12345' // 使用固定的测试openid
    const testUnionid = 'test_unionid_12345' // 使用固定的测试unionid
    
    // 查询现有用户
    let user = await User.findOne({
      where: { wechatOpenid: testOpenid }
    })

    if (!user) {
      // 处理邀请码
      let inviterId = null
      if (invitationCode) {
        const inviter = await User.findOne({
          where: { invitation_code: invitationCode }
        })

        if (inviter) {
          inviterId = inviter.id
        }
      }

      // 生成用户邀请码
      const generateInvitationCode = () => {
        const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        let code = ''
        for (let i = 0; i < 6; i++) {
          code += chars.charAt(Math.floor(Math.random() * chars.length))
        }
        return code
      }

      // 从微信用户信息中获取昵称和头像
      const nickname = userInfo?.nickName || `微信用户${Math.random().toString(36).substring(7)}`
      const avatar = userInfo?.avatarUrl || null

      // 创建新用户
      user = await User.create({
        phone: null, // 明确设置为null
        wechatOpenid: testOpenid,
        wechatUnionid: testUnionid,
        nickname: nickname,
        avatar: avatar,
        gender: userInfo?.gender === 1 ? 'male' : userInfo?.gender === 2 ? 'female' : 'unknown',
        invitationCode: generateInvitationCode(),
        inviterId: inviterId,
        status: 1
      })

      logger.info(`创建新微信用户: ID=${user.id}, nickname=${nickname}`)
    } else {
      // 用户已存在，更新用户信息（如果提供了新的用户信息）
      if (userInfo) {
        const updateData = {}
        if (userInfo.nickName && userInfo.nickName !== user.nickname) {
          updateData.nickname = userInfo.nickName
        }
        if (userInfo.avatarUrl && userInfo.avatarUrl !== user.avatar) {
          updateData.avatar = userInfo.avatarUrl
        }
        if (userInfo.gender !== undefined) {
          const genderValue = userInfo.gender === 1 ? 'male' : userInfo.gender === 2 ? 'female' : 'unknown'
          if (genderValue !== user.gender) {
            updateData.gender = genderValue
          }
        }

        if (Object.keys(updateData).length > 0) {
          await user.update(updateData)
          logger.info(`更新微信用户信息: ID=${user.id}, 更新字段=${Object.keys(updateData).join(',')}`)
        }
      }

      logger.info(`微信用户登录: ID=${user.id}, nickname=${user.nickname}`)
    }

    // 更新最后登录时间
    await user.update({ last_login: new Date() })

    // 重新查询用户以获取最新数据
    user = await User.findByPk(user.id)

    // 生成token
    const token = jwt.sign(
      { id: user.id },
      process.env.JWT_SECRET || 'your-jwt-secret',
      { expiresIn: '7d' }
    )

    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          id: user.id,
          phone: user.phone,
          nickname: user.nickname,
          avatar: user.avatar,
          gender: user.gender,
          points: user.points,
          memberLevel: user.member_level,
          invitationCode: user.invitation_code,
          role: user.role,
          status: user.status,
          openid: user.wechatOpenid,
          isNewUser: !user.phone // 是否为新用户(未绑定手机号)
        }
      }
    })
  } catch (error) {
    logger.error('Wechat login error:', error)
    res.status(500).json({
      success: false,
      message: '微信登录失败，请稍后再试'
    })
  }
})

/**
 * @api {get} /api/auth/verify 验证token
 * @apiDescription 验证用户token是否有效
 * @apiName VerifyToken
 * @apiGroup Auth
 * @apiHeader {String} Authorization Bearer token
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 用户基本信息
 */
router.get('/verify', auth, async (req, res) => {
  try {
    const userId = req.user.id

    const user = await User.findByPk(userId, {
      attributes: ['id', 'phone', 'nickname', 'avatar', 'points', 'member_level', 'role', 'status']
    })

    if (!user || user.status !== 1) {
      return res.status(401).json({
        success: false,
        message: '用户不存在或已被禁用'
      })
    }

    res.json({
      success: true,
      message: 'Token验证成功',
      data: {
        id: user.id,
        phone: user.phone,
        nickname: user.nickname,
        avatar: user.avatar,
        points: user.points,
        memberLevel: user.member_level,
        role: user.role,
        status: user.status
      }
    })
  } catch (error) {
    logger.error('Verify token error:', error)
    res.status(401).json({
      success: false,
      message: 'Token验证失败'
    })
  }
})

/**
 * @api {get} /api/auth/profile 获取用户信息
 * @apiDescription 获取当前登录用户的详细信息
 * @apiName GetAuthProfile
 * @apiGroup Auth
 * @apiHeader {String} Authorization Bearer token
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 用户详细信息
 */
router.get('/profile', auth, async (req, res) => {
  try {
    const userId = req.user.id

    const user = await User.findByPk(userId, {
      attributes: [
        'id', 'phone', 'nickname', 'avatar', 'gender', 'birthday',
        'points', 'member_level', 'invitation_code', 'role', 'status', 'created_at'
      ]
    })

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      })
    }

    res.json({
      success: true,
      data: {
        id: user.id,
        phone: user.phone,
        nickname: user.nickname,
        avatar: user.avatar,
        gender: user.gender,
        birthday: user.birthday,
        points: user.points,
        memberLevel: user.member_level,
        invitationCode: user.invitation_code,
        role: user.role,
        status: user.status,
        createdAt: user.created_at
      }
    })
  } catch (error) {
    logger.error('Get auth profile error:', error)
    res.status(500).json({
      success: false,
      message: '获取用户信息失败'
    })
  }
})

/**
 * @api {post} /api/auth/logout 用户登出
 * @apiDescription 用户登出接口
 * @apiName Logout
 * @apiGroup Auth
 * @apiHeader {String} Authorization Bearer token
 * @apiSuccess {Boolean} success 是否成功
 */
router.post('/logout', auth, async (req, res) => {
  try {
    // 这里可以添加token黑名单逻辑
    // 目前只是简单返回成功
    res.json({
      success: true,
      message: '登出成功'
    })
  } catch (error) {
    logger.error('Logout error:', error)
    res.status(500).json({
      success: false,
      message: '登出失败'
    })
  }
})

module.exports = router
